<?php

class Story extends AppModel {
	
	const PUBLISHED = 1;
	const DRAFT = 2;
	
	public $name = 'Story';
	
	public $displayField = 'title';
	
	public $belongsTo = array(
		'Author',
		'Category' => array(
			'className' => 'StoryCategory',
			'foreignKey' => 'category_id'
		)
	);
	
	public function afterFind($results, $primary = false) {
		
		//parent::afterFind($results, $primary);
		foreach($results as $k => $result) {
			// story excerpt
			if( isset($result[$this->alias]) && isset($result[$this->alias]['body']) ) {
				$excerpt = preg_replace("/<img[^>]+\>/i", "", $result[$this->alias]['body']);
				$excerpt = $this->truncateText($excerpt, 850);
				$results[$k][$this->alias]['excerpt'] = $excerpt;
			}
			else if( isset($result['body']) ) {
				$excerpt = preg_replace("/<img[^>]+\>/i", "", $result['body']);
				$excerpt = $this->truncateText($excerpt, 850);
				$results[$k]['excerpt'] = $excerpt;
			}
		}
		
		return $results;
	}
	
	public function beforeSave($options = array()) {
		if( isset($this->data[$this->name]['title']) ) {
			// story slug
			$title = strtolower($this->data[$this->name]['title']);
			$this->data[$this->name]['slug'] = Inflector::slug($title, '-');
		}
		return parent::beforeSave($options);
	}
	
}